<script setup>
import { onMounted, ref, computed } from "vue";
import { ElMessage } from "element-plus";
import { getMajor, updateMajor, dropMajor, insertMajor } from "@/apis/manger";

const allMajors = ref([]);
const majors = ref([]);
const queryName = ref(null);
const currentPage = ref(1);
const pageSize = ref(5);
const totalMajors = computed(() => allMajors.value.length);

const isEditDialogVisible = ref(false);
const isAddDialogVisible = ref(false);


const currentMajor = ref({
  id: "",
  name: "",
  description: "",
});

onMounted(() => {
  fetchMajors();
});


async function fetchMajors() {
  try {
    let result = await getMajor(queryName.value);
    console.log(result);
    allMajors.value = result.result;
    updateMajors();
  } catch (error) {
    ElMessage.error("获取专业列表失败");
    console.error("Error fetching majors:", error);
  }
}


function updateMajors() {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  majors.value = allMajors.value.slice(start, end);
}

const onQueryChange = () => {
  currentPage.value = 1; // Reset to the first page
  fetchMajors();
};

const onPageChange = (page) => {
  currentPage.value = page;
  updateMajors();
};

const onPageSizeChange = (size) => {
  pageSize.value = size;
  updateMajors();
};

const editMajor = (major) => {
  currentMajor.value = { ...major }; // Set the current major for editing
  isEditDialogVisible.value = true; // Show the edit dialog
};

// Save the edited major
const saveMajorEdit = async () => {
  try {
    let result = await updateMajor(currentMajor.value);
    if (result.message === "200") {
      allMajors.value = allMajors.value.map((m) =>
          m.id === currentMajor.value.id ? currentMajor.value : m
      );
      updateMajors();
      ElMessage.success("编辑成功");
      isEditDialogVisible.value = false; // Close the dialog
    } else {
      ElMessage.error("编辑失败");
    }
  } catch (error) {
    ElMessage.error("编辑失败");
    console.error("Error editing major:", error);
  }
};

// Delete a major
const deleteMajor = async (major) => {
  try {
    let result = await dropMajor(major.id);
    if (result.message === "200") {
      allMajors.value = allMajors.value.filter((m) => m.id !== major.id);
      updateMajors();
      ElMessage.success("删除成功");
    } else {
      ElMessage.error("该专业已有学生，拒绝删除");
    }
  } catch (error) {
    ElMessage.error("删除失败");
    console.error("Error deleting major:", error);
  }
};

// Add a new major
const addMajor = () => {
  currentMajor.value = { id: "", name: "", description: "" }; // Reset the major object
  isAddDialogVisible.value = true; // Show the add dialog
};

// Save the new major
const saveNewMajor = async () => {
  try {
    let result = await insertMajor(currentMajor.value);
    if (result.message === "200") {
      allMajors.value.push(result.result);
      updateMajors();
      ElMessage.success("新增成功");
      isAddDialogVisible.value = false; // Close the dialog
    } else {
      ElMessage.error("新增失败");
    }
  } catch (error) {
    ElMessage.error("新增失败");
    console.error("Error adding major:", error);
  }
};
</script>

<template>
  <el-card>
    <div style="margin-bottom: 16px;">
      <el-input
          v-model="queryName"
          placeholder="查询专业名称"
          style="width: 200px; margin-right: 16px;"
      ></el-input>
      <el-button type="primary" @click="onQueryChange">查询</el-button>
    </div>
    <el-button type="primary" @click="addMajor">新增专业</el-button>
    <el-table :data="majors" style="width: 100%">
      <el-table-column label="专业名称" prop="name"></el-table-column>
      <el-table-column label="专业编号" prop="id"></el-table-column>
      <el-table-column label="专业简介" prop="description"></el-table-column>
      <el-table-column label="操作">
        <template v-slot="scope">
          <el-button @click="editMajor(scope.row)" size="small">编辑</el-button>
          <el-button @click="deleteMajor(scope.row)" size="small" type="danger">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :total="totalMajors"
        @current-change="onPageChange"
        @size-change="onPageSizeChange"
        layout="total, sizes, prev, pager, next, jumper"
        style="margin-top: 16px;"
    ></el-pagination>

    <!-- Edit Major Dialog -->
    <el-dialog v-model="isEditDialogVisible" title="编辑专业">
      <el-form :model="currentMajor">
        <el-form-item label="专业编号">
          <el-input v-model="currentMajor.id" readonly></el-input>
        </el-form-item>
        <el-form-item label="专业名称">
          <el-input v-model="currentMajor.name"></el-input>
        </el-form-item>
        <el-form-item label="专业简介">
          <el-input v-model="currentMajor.description"></el-input>
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <el-button @click="isEditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveMajorEdit">保存</el-button>
      </template>
    </el-dialog>

    <!-- Add Major Dialog -->
    <el-dialog v-model="isAddDialogVisible" title="新增专业">
      <el-form :model="currentMajor">
        <el-form-item label="专业名称">
          <el-input v-model="currentMajor.name"></el-input>
        </el-form-item>
        <el-form-item label="专业简介">
          <el-input v-model="currentMajor.description"></el-input>
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <el-button @click="isAddDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveNewMajor">保存</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<style scoped>
</style>
